from twisted.internet import protocol
from twisted.protocols.memcache import MemCacheProtocol
import pickle

class CacheManager :
    
    cache = None
    
    def __init__(self,reactor,host,port):
        if not CacheManager.cache :
            self.client = protocol.ClientCreator(reactor,MemCacheProtocol).connectTCP(host, port)
            CacheManager.cache = self
    
    @staticmethod
    def getInstance():
        return CacheManager.cache;

    def store(self,key,value,callback):
        self.client.addCallback(self.__store,key,value,callback)
    
    def __store(self,protocal,key,value,callback):
        def callbackWrapper(result):
            callback(result)  
        d = protocal.set(key,pickle.dumps(value))
        d.addCallback(callbackWrapper)
        return protocal
    
    def fetch(self,key,callback):
        self.client.addCallback(self.__fetch,key,callback)
    
    def __fetch(self,protocal,key,callback):
        def callbackWrapper(result):
            param = None
            if result[1] :
                param = pickle.loads(result[1])
            callback(param)   
        d = protocal.get(key)
        d.addCallback(callbackWrapper)
        return protocal
    
    def delete(self,key,callback):
        self.client.addCallback(self.__delete,key,callback)
    
    def __delete(self,protocal,key,callback):
        def callbackWrapper(result):
            param = None
            if result[1] :
                param = pickle.loads(result[1])
            callback(param) 
        d = protocal.delete(key)
        d.addCallback(callbackWrapper)
        return protocal